/** @format */

import { PRIZE_TYPE, DRAW_STATUS, C_APP_NAME, TBERROR, CODE_TYPES } from '../../constants'
import { TBAPIS, resultsModel } from '../../sdk'
import { CodeType } from 'taobao-mini-sdk/lib/utils/codetypes'

/**
 * 发奖，包含权益，实物，积分
 * @param {*} document 必须要有{ type, ename, _id }
 * @param {*} session
 * @param {*} context
 */
export const sendTBAward = async (
  context: IContext<IParams>,
  session: string,
  awardInfo: IAwards
): Promise<IAwards | CodeType> => {
  let { type, ename, _id, credits } = awardInfo
  if (!type) {
    return CODE_TYPES.PARAMS_ERROR
  }
  if (type === PRIZE_TYPE.OBJECT) {
    return awardInfo
  }

  console.log(`type`, type)
  // 若中奖为权益
  if (type === PRIZE_TYPE.ENAME) {
    console.log(`中权益`)
    let { drawStatus, remark } = await sendEname(ename, _id, session, context)
    console.log(`drawStatus, remark`, drawStatus, remark)
    awardInfo.drawStatus = drawStatus
    awardInfo.remark = remark
  }
  if (type === PRIZE_TYPE.CREDITS) {
    let { drawStatus, remark } = await sendCredits(credits, session, context)
    awardInfo.drawStatus = drawStatus
    awardInfo.remark = remark
  }
  return awardInfo
}

/**
 * 发放积分
 * @param {发放的积分数} credits
 * @param {*} session
 * @param {*} context
 * @returns {drawStatus, remark}
 */
export const sendCredits = async (credits: number, session: string, context: IContext<IParams>) => {
  let drawStatus = 0
  let remark = ''
  let result = await TBAPIS.changeCredits(context, {
    quantity: credits,
    change_type: 2,
    opt_type: '0',
    remark: `参与活动加积分`
  })
  if (result) {
    drawStatus = DRAW_STATUS.SUCCESS
  } else {
    drawStatus = DRAW_STATUS.FAIL
    remark = result.result_msg
  }
  return { drawStatus, remark }
}
/**
 * @desc 发放权益
 * @param {权益名称} ename
 * @param {唯一key} uniqueId
 * @param {*} session
 * @param {*} context
 * @returns { drawStatus, remark }
 */

export const sendEname = async (ename: string, uniqueId: string, session: string, context: IContext<IParams>) => {
  let result = {
    result_success: '',
    result_code: '',
    msg: '',
    result_msg: '',
    sub_msg: ''
  }
  try {
    result = await TBAPIS.benefitSend(context, {
      right_ename: ename,
      receiver_id: context.openId,
      unique_id: uniqueId,
      app_name: C_APP_NAME,
      session
    })
  } catch (e) {
    console.log(`发放权益失败`, e)
    result = e
  }

  let drawStatus = 0
  let remark = ''
  if (result.result_success) {
    drawStatus = DRAW_STATUS.SUCCESS
  } else {
    let result_code = result.result_code
    if (
      [
        'APPLY_SINGLE_COUPON_COUNT_EXCEED_LIMIT',
        'APPLY_ONE_SELLER_COUNT_EXCEED_LIMIT',
        'USER_PERMISSION_EXCEED_MAX_RIGHT_COUNT_IN_DAY'
      ].includes(result_code)
    ) {
      drawStatus = DRAW_STATUS.RETRY
    } else {
      drawStatus = DRAW_STATUS.FAIL
    }
    remark = TBERROR[result_code || result.msg] || result.result_msg || result.sub_msg || `发放失败`
  }
  return { remark, drawStatus }
}
